<template>
  <div class="pages" @mousedown.stop.prevent.left="start($event)"
    @mousemove.stop.prevent.left="drag($event)" @mouseup.stop.prevent.left="end($event)"
    @mouseleave.stop.prevent.left="fix($event)">
    <div class="seatSelectArea" ref="seatSelectArea">
      <div class="seatArea" :style="{
          width: seatAreaWidth + 30 + 'px',
          height: seatAreaHeight + 20 + 'px',
          padding: '20px 0 0 20px',
          overflow: 'hidden'
        }" v-show="x !== 0 && y !== 0">
        <div v-for="(seatItem, index) in seatList" :key="index">
          <div ref="seatItem" :x="seatItem.x" :y="seatItem.y" class="seatItem" :style="{
              width: seatItemWidth + 'px',
              height: seatItemWidth + 'px',
              transform:
                'translate3d(' +
                seatItem.translateX +
                'px,' +
                seatItem.translateY +
                'px,0px)',
              background: seatItem.background,
              overflow: 'hidden'
            }">
            <el-tooltip effect="dark" :content="seatItem.y + '-' + seatItem.x"
              placement="top-start">
              <span class="gaksd">{{ seatItem.y + "-" + seatItem.x }}</span>
            </el-tooltip>
            <img v-if="seatItem.backimg" :src="ipAddress + seatItem.backimg" />
          </div>
        </div>
      </div>
      <drag-div :left="left" :top="top" :width="width" :height="height"
        v-show="showDrag"></drag-div>
    </div>
  </div>
</template>

<script>
import { mapMutations, mapActions, mapState } from "vuex";
import DragDiv from "./DragDiv";
export default {
  name: "CoordinateSystem",
  components: {
    DragDiv,
  },
  props: ["prop_x", "prop_y", "prop_seatList", "loading", "ipAddress"],
  data() {
    return {
      seatItemWidth: 40,
      shifting: 10, // 偏移值
      left: 0,
      top: 0,
      width: 0,
      height: 0,
      startX: 0,
      startY: 0,
      showDrag: false,
      seatList: [],
      seatListBack: null,
      unSelect: "#C6E2FF",
      selecting: "#409EFF",
      selected: "#E9EEF3",
      timer: null,
      x: 0,
      y: 0,
      templeteId: null,
    };
  },
  watch: {
    prop_seatList(value) {
      this.seatListBack = value;
    },
    prop_x(value) {
      this.x = value;
      this.refreshDom();
    },
    prop_y(value) {
      this.y = value;
      this.refreshDom();
    },
  },
  computed: {
    seatAreaWidth() {
      return (
        (this.seatItemWidth + this.shifting) * (this.x + 0.3) - this.shifting
      );
    },
    seatAreaHeight() {
      return (
        (this.seatItemWidth + this.shifting) * (this.y + 0.3) - this.shifting
      );
    },
    translateValue() {
      return this.seatItemWidth + this.shifting;
    },
    ...mapState({
      region: (state) => state.hallSeat.region,
      hallSeatSeatList: (state) => state.hallSeat.seatList,
      hallSeatX: (state) => state.hallSeat.x,
      hallSeatY: (state) => state.hallSeat.y,
      getSeattypecolor: (state) => state.hallSeat.getSeattypecolor,
    }),
  },
  methods: {
    ...mapActions(["SETLOADING", "MAKELIST"]),
    ...mapMutations(["changeX", "changeY", "setSeatList", "upNc"]),
    refreshDom() {
      let that = this;
      let seatScale = 1;
      let seatScaleX = 1;
      let seatScaleY = 1;
      let seatSelectAreaWidth = that.$refs.seatSelectArea.offsetWidth;
      let seatSelectAreaHeight = that.$refs.seatSelectArea.offsetHeight;
      let seatAreaWidth = 50 * that.x - that.shifting;
      let seatAreaHeight = 50 * that.y - that.shifting;
      if (seatAreaWidth > seatSelectAreaWidth) {
        seatScaleX = seatSelectAreaWidth / seatAreaWidth;
      }
      if (seatAreaHeight > seatSelectAreaHeight) {
        seatScaleY = seatSelectAreaHeight / seatAreaHeight;
      }
      if (seatScaleX < 1 || seatScaleY < 1) {
        seatScale = seatScaleX < seatScaleY ? seatScaleX : seatScaleY;
      }
      that.seatItemWidth = 40 * seatScale;
      that.shifting = 10 * seatScale;
      that.seatList = [];
      for (let x = 1; x <= that.x; x++) {
        for (let y = 1; y <= that.y; y++) {
          var data = {};
          data = {
            x: x,
            y: y,
            translateX: that.translateValue * (x - 1),
            translateY: that.translateValue * (y - 1),
            background: this.unSelect,
            backimg: null,
            type: -1, //0过道 1普通 2VIP 3空位置
            c_theater_id: 0,
          };
          that.seatList.push(data);
        }
      }
      this.$nextTick(() => {
        if ("seatItem" in that.$refs) {
          for (const item of that.$refs.seatItem) {
            let clientRect = item.getBoundingClientRect();
            let index = that.seatList.findIndex(
              (el) =>
                el.x === parseInt(item.attributes.x.value) &&
                el.y === parseInt(item.attributes.y.value)
            );
            that.seatList.forEach((i, ii, arr) => {
              if (ii == index) {
                i.top = clientRect.top;
                i.bottom = clientRect.bottom;
                i.left = clientRect.left;
                i.right = clientRect.right;
              }
            });
          }
        }
      });
    },
    seatRender() {
      this.$nextTick(() => {
        let arr = this.hallSeatSeatList.filter((i) => i.id == this.region.id)[0]
          .listseat;
        arr.forEach((i) => {
          this.seatList.forEach((j) => {
            if (i.x_axis == j.x && i.y_axis == j.y) {
              j.type = i.ticket_type;
              j.background = this.unSelect;
              j.backimg = i.colour;
              j.pitch_on_color = i.pitch_on_color;
            }
          });
        });
      });
    },
    start(e) {
      let that = this;
      // 解决mousedown导致click失效
      if (that.timer) {
        clearTimeout(that.timer);
      }
      that.timer = setTimeout(function () {
        that.showDrag = true;
      }, 100);
      let x = e.clientX;
      let y = e.clientY;
      that.left = x;
      that.top = y;
      that.startX = x;
      that.startY = y;
    },
    drag(e) {
      let that = this;
      if (that.showDrag) {
        let x = e.clientX;
        let y = e.clientY;
        that.left = Math.min(x, that.startX);
        that.top = Math.min(y, that.startY);
        that.width = Math.abs(x - that.startX);
        that.height = Math.abs(y - that.startY);
      }
    },
    fix() {
      if (this.showDrag) {
        let that = this;
        that.left = 0;
        that.top = 0;
        that.width = 0;
        that.height = 0;
        that.startX = 0;
        that.startY = 0;
        that.showDrag = false;
      }
    },
    end() {
      clearTimeout(this.timer);
      if (this.showDrag) {
        // 首先求出 `元素左上角` 与 `选框左上角` 在X方向较大值与Y方向较大值的交点，记为M点
        // 然后求出 `元素右下角` 与` 选框右下角` 在X方向较小值与Y方向较小值的交点，记为N点。
        // 如果M点的X坐标和Y坐标值均比N点相应的X坐标和Y坐标值小，亦即M和N可以分别构成一个矩形的左上角点和右上角点，则两矩形相交；其余情况则不相交。
        let that = this;
        let seatList = that.seatList;
        let dragX0 = that.left;
        let dragY0 = that.top;
        let dragX1 = that.left + that.width;
        let dragY1 = that.top + that.height;
        for (const index in seatList) {
          let mX = Math.max(dragX0, seatList[index].left);
          let mY = Math.max(dragY0, seatList[index].top);
          let nX = Math.min(dragX1, seatList[index].right);
          let nY = Math.min(dragY1, seatList[index].bottom);
          if (mX < nX && mY < nY) {
            if (that.seatList[index].background === that.selecting) {
              if (
                that.seatList[index].backimg === "" ||
                that.seatList[index].backimg === null
              ) {
                that.seatList[index].background = that.unSelect;
              } else {
                that.seatList[index].background = that.selected;
              }
            } else if (that.seatList[index].background === that.unSelect) {
              that.seatList[index].background = that.selecting;
              that.seatList[index].backimg = "";
            } else if (that.seatList[index].background === that.selected) {
              that.seatList[index].background = that.selecting;
            }
          }
        }
        that.left = 0;
        that.top = 0;
        that.width = 0;
        that.height = 0;
        that.startX = 0;
        that.startY = 0;
        that.showDrag = false;
      }
    },
    markSeats(e) {
      let that = this;
      let seatList = that.seatList;
      for (const index in seatList) {
        if (that.seatList[index].background === that.selecting) {
          that.seatList[index].background = that.unSelect;
          that.seatList[index].backimg = e.unselectedColor;
          that.seatList[index].pitch_on_color = e.selectedColor;
          that.seatList[index].type = e.id;
        }
      }

      let obj = {
        areaname: that.region.areaname,
        id: that.region.id,
        listseat: this.seatList,
      };
      that.upNc(that.region);
      that.setSeatList(obj);
    },
    confirm() {
      this.hallSeatSeatList.forEach((i, ii, iii) => {
        iii[ii].listseat.forEach((k) => {
          k.seat_state = k.ticket_type == -1 ? -1 : 0;
        });
        // X 列
        // Y 行
        let jobs = i.listseat.filter((k) => k.ticket_type != -1);
        let jobs2 = i.listseat.filter((k) => k.ticket_type == -1);
        let map = {};
        let jobarr = [];
        for (var i = 0; i < jobs.length; i++) {
          var ai = jobs[i];
          if (!map[ai.y_axis]) {
            jobarr.push({
              y_axis: ai.y_axis,
              item: [ai],
            });
            map[ai.y_axis] = ai;
          } else {
            for (var j = 0; j < jobarr.length; j++) {
              var dj = jobarr[j];
              if (dj.y_axis == ai.y_axis) {
                dj.item.push(ai);
                break;
              }
            }
          }
        }

        jobarr.forEach((o, oo) => {
          o.item.forEach((p, pp, ppp) => {
            p.seatrow = o.y_axis; //行
            p.seatcolumn = pp + 1; //列
          });
        });
        iii[ii].rownum = this.hallSeatX;
        iii[ii].columnnum = this.hallSeatY;
        let newArr = [];
        jobarr.forEach((j) => {
          newArr.push(...j.item);
        });

        iii[ii].listseat = [...newArr, ...jobs2];
      });
      let parma = {
        venname: this.$route.query.venue,
        arealist: this.hallSeatSeatList,
      };
      this.http.post("/api/cinemaSeat/SeatUpdate", parma).then((res) => {
        if (res.status) {
          this.$Message.success(res.message);
        } else {
          this.$Message.error(res.message);
        }
      });
    },
  },
};
</script>
<style lang="less" scoped>
.pages {
  width: 100%;
  height: 100vh;
  padding: 100px 50px;
  box-sizing: border-box;

  .seatSelectArea {
    width: 100%;
    height: 100%;
    position: relative;
  }

  .seatArea {
    display: flex;
    flex-wrap: wrap;
    margin: 0 auto;
    padding: 5px;
    border: 2px dashed rgba(0, 0, 0, 0.2);
    border-radius: 5px;

    .seatItem {
      position: absolute;
      color: white;
      line-height: 40px;
      border-radius: 5px;
      user-select: none;
      display: flex;
      .gaksd {
        position: absolute;
      }
      img {
        width: 100%;
        height: 100%;
        border: none;
        object-fit: cover;
      }
    }
  }
}
</style>
